package com.bird.设计模式.创建型.单例模式.懒汉单例;

/**
 * @data 2022/2/17 17:09
 * @author: bird
 * @description: 双重检查机制创建单例：
 * 方式 解决懒汉式单例的线程安全的问题和兼顾性能的问题
 */
public class LazyDoubleCheckSingleton {

    // volatile 防止重排序
    private volatile static LazyDoubleCheckSingleton lazyDoubleCheckSingleton = null;

    private LazyDoubleCheckSingleton() {
    }


    // 双重检查机制 这个创建对象的实例是线程安全的
    public static LazyDoubleCheckSingleton getInstance() {
        if (null == lazyDoubleCheckSingleton) {
            synchronized (LazyDoubleCheckSingleton.class) {
                if (null == lazyDoubleCheckSingleton) {
                    lazyDoubleCheckSingleton = new LazyDoubleCheckSingleton();
                    // 这里其实是执行三个步骤
                    //1：分配内存给这个对象
                    //2: 设置lazyDoubleCheckSingleton执向刚分配的内存
                    //3: 初始化对象
                }
            }
        }
        return lazyDoubleCheckSingleton;
    }
}
